package com.neusoft.neuiotms.dcom.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.QuestionnaireDTO;
import com.neusoft.neuiotms.dcom.dto.QuestionnaireFeedbackDTO;
import com.neusoft.neuiotms.dcom.model.Questionnaire;
import com.neusoft.neuiotms.dcom.repository.QuestionnaireRepository;

@Component
public class QuestionnaireConverter extends AbstractConverter<Questionnaire, QuestionnaireDTO> {

    @Autowired
    private QuestionnaireRepository questionnaireRepository;

    @Override
    public Questionnaire toModel(final QuestionnaireDTO dto) {

        Questionnaire model;

        if (dto.isNew()) {
            model = new Questionnaire();
        } else {
            model = this.questionnaireRepository.getOne(dto.getId());
        }
        model.setGroupCode(dto.getGroupCode());
        model.setTitle(dto.getTitle());
        model.setYear(dto.getYear());
        model.setScope(dto.getScope());
        model.setType(dto.getType());
        model.setClosedAt(dto.getClosedAt());

        return model;
    }

    @Override
    public QuestionnaireDTO toDTO(final Questionnaire model, final boolean forListView) {

        final QuestionnaireDTO dto = new QuestionnaireDTO();

        dto.setId(model.getId());
        dto.setGroupCode(model.getGroupCode());
        dto.setTitle(model.getTitle());
        dto.setYear(model.getYear());
        dto.setScope(model.getScope());
        dto.setType(model.getType());
        dto.setClosedAt(model.getClosedAt());
        dto.setPublished(model.isPublished());
        dto.setPublishAt(model.getPublishAt());

        if (!forListView) {
            model.getFeedbacks().forEach(feed -> {
                final QuestionnaireFeedbackDTO feedDto = new QuestionnaireFeedbackDTO();
                feedDto.setId(feed.getId());
                feedDto.setUser(feed.getUser());
                feedDto.setUsername(feed.getUsername());
                feedDto.setQuestionnaireId(model.getId());
                feedDto.setContent(feed.getContent());
                feedDto.setSubmitted(feed.isSubmitted());
                feedDto.setSubmitAt(feed.getSubmitAt());
                dto.getFeedbacks().add(feedDto);
            });
        }

        return dto;
    }

}
